package com.task.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.task.entity.dto.*;
import com.task.entity.po.*;
import com.task.entity.vo.AdviceVO;
import com.task.entity.vo.CountInfoVO;
import com.task.entity.vo.HomeCategoryVO;
import com.task.mapper.CommonMapper;
import com.task.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/index")
public class HomeController {
    @Autowired
    private CommonMapper commonMapper;

    private static String UPLOADED_FOLDER = "D:\\pictures\\"; // 上传文件的保存路径

    @PostMapping("/list")
    public R homeList() {
        List<HomeCategoryVO> categoryVOList = commonMapper.listIndex();
        categoryVOList.remove(0);

        categoryVOList.forEach(obj -> {
            String type = commonMapper.queryType(obj.getArea());
            if (StrUtil.isNotEmpty(type)) {
                obj.setType(type);
            }
        });

        return R.SUCCESS("获取成功!", categoryVOList);
    }


    @PostMapping("/recommend_list")
    public R recommendList() {
        List<HomeCategoryVO> categoryVOList = commonMapper.recommendList();
        categoryVOList.remove(0);

        categoryVOList.forEach(obj -> {
            String type = commonMapper.queryType(obj.getArea());
            if (StrUtil.isNotEmpty(type)) {
                obj.setType(type);
            }
        });

        return R.SUCCESS("获取成功!", categoryVOList);
    }

    @PostMapping("/detail")
    public R detail(@RequestParam("id") Long id) {
        HomeCategoryVO homeCategoryVO = commonMapper.queryById(id);
        return R.SUCCESS("获取成功!", homeCategoryVO);
    }

    @PostMapping("/top")
    public R topHomeInfo() {
        List<HomeCategoryVO> categoryVOList = commonMapper.listIndex();
        return R.SUCCESS("获取成功!", categoryVOList.get(0));
    }


    @PostMapping("/uploadAvatar")
    public String singleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空，请选择一个文件上传。";
        }

        try {
            // 获取文件并保存到服务器
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);


            return file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }


    @PostMapping("/register")
    public R register(@RequestBody AddUserDTO dto) {
        UserPO user = commonMapper.queryByUserName(dto.getUsername());
        if (user != null) {
            return R.FAILED("该用户已存在");
        }


        UserPO po = new UserPO();
        po.setId(IdUtil.getSnowflakeNextId());
        BeanUtils.copyProperties(dto, po);
        po.setImage(dto.getAvatarUrl());

        commonMapper.insertUser(po);

        return R.SUCCESS("注册成功!");
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginDTO dto) {

        UserPO po = commonMapper.queryByUserName(dto.getUsername());
        if (po == null) {
            return R.FAILED("该用户不存在!");
        }

        String password = po.getPassword();
        if (!password.equals(dto.getPassword())) {
            return R.FAILED("密码错误!");
        }

        return R.SUCCESS("登录成功!").setData(po);
    }


    @PostMapping("/add_trip")
    public R addTrip(@RequestBody AddTripDTO dto) {

        TripPO existPo = commonMapper.queryTripByUserIdAndScenery(dto.getUserId(), dto.getSceneryId());
        if (existPo != null) {
            return R.FAILED("您已添加过该景点!");
        }


        TripPO tripPO = new TripPO();
        tripPO.setId(IdUtil.getSnowflakeNextId());
        tripPO.setUserId(dto.getUserId());
        tripPO.setSceneryId(dto.getSceneryId());
        tripPO.setCreateDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        tripPO.setIsOrder(0);
        commonMapper.insertTrip(tripPO);

        return R.SUCCESS("添加成功!");
    }


    @PostMapping("/delete_trip")
    public R deleteTrip(@RequestBody AddTripDTO dto) {

        commonMapper.deleteTrip(dto.getSceneryId(), dto.getUserId());

        return R.SUCCESS("删除成功!");
    }

    @PostMapping("/already_end_trip")
    public R alreadyEndTrip(@RequestBody AddTripDTO dto) {

        commonMapper.updateEndTrp(dto.getSceneryId(), dto.getUserId());

        return R.SUCCESS("确认出行成功!");
    }


    @PostMapping("/list_trip")
    public R listTrip(@RequestBody QueryTripDTO dto) {

        List<TripPO> tripPOList = commonMapper.listTrip(dto.getUserId(), dto.getType());

        List<HomeCategoryVO> categoryVOList = commonMapper.listIndex();

        Map<Long, HomeCategoryVO> categoryVOMap = categoryVOList.stream()
                .collect(Collectors.toMap(
                        HomeCategoryVO::getId,
                        Function.identity(),
                        (existing, replacement) -> existing // 在遇到重复键时保留现有的值
                ));


        List<HomeCategoryVO> resultList = new ArrayList<>();
        tripPOList.forEach(obj -> {
            HomeCategoryVO vo = new HomeCategoryVO();
            HomeCategoryVO categoryVO = categoryVOMap.get(obj.getSceneryId());
            if (categoryVO != null) {
                BeanUtils.copyProperties(categoryVO, vo);
                vo.setSceneryId(obj.getSceneryId());
                resultList.add(vo);
            }
        });

        return R.SUCCESS("获取成功!").setData(resultList);
    }


    @PostMapping("/add")
    public R addTravel(@RequestBody AddTravelDTO dto) {

        TravelPO travelPO = new TravelPO();
        BeanUtils.copyProperties(dto, travelPO);
        travelPO.setId(IdUtil.getSnowflakeNextId());
        travelPO.setCreateDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        commonMapper.insertTravel(travelPO);

        return R.SUCCESS("添加成功!");
    }


    @PostMapping("/list_travel")
    public R listTravel(@RequestParam("type") String type) {

        List<TravelPO> listTravel = commonMapper.listTravel(type);
        return R.SUCCESS("获取成功!", listTravel);
    }

    @PostMapping("/list_travel_user")
    public R listTravelUserId(@RequestParam("userId") String userId) {
        List<TravelPO> listTravelAll = commonMapper.listTravelAll(userId);
        return R.SUCCESS("获取成功!", listTravelAll);

    }

    @PostMapping("/delete_travel")
    public R deleteTravel(@RequestBody DeleteDTO dto){

        commonMapper.deleteTravel(dto);
        return R.SUCCESS("删除成功!");
    }

    @PostMapping("/delete_travel_collect")
    public R deleteTravelCollect(@RequestBody DeleteDTO dto){

        commonMapper.deleteTravelCollect(dto);
        return R.SUCCESS("删除成功!");
    }


    @PostMapping("/list_collect")
    public R listCollect(@RequestParam("userId") String userId) {
        List<TravelPO> listCollect = commonMapper.listCollect(userId);
        return R.SUCCESS("获取成功!", listCollect);
    }


    @PostMapping("/addTravelCollect")
    public R addTravelCollect(@RequestBody AddTravelCollectDTO dto) {

        CollectPO collectPO = new CollectPO();
        collectPO.setId(IdUtil.getSnowflakeNextId());
        collectPO.setTravelId(dto.getId());
        collectPO.setUserId(dto.getUserId());
        collectPO.setCreateDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        commonMapper.insertTravelCollect(collectPO);

        return R.SUCCESS("收藏成功!");
    }


    @PostMapping("/getUserInfo")
    public R userInfo(@RequestParam("userId") String userId) {
        UserPO userInfo = commonMapper.getUserInfo(userId);

        List<TravelPO> listTravelAll = commonMapper.listTravelAll(userId);
        List<TravelPO> listCollect = commonMapper.listCollect(userId);

        if (CollectionUtil.isNotEmpty(listCollect)) {
            userInfo.setCollectNum(listCollect.size());
        } else {
            userInfo.setCollectNum(0);
        }

        if (CollectionUtil.isNotEmpty(listTravelAll)) {
            userInfo.setReadNum(listTravelAll.size());
        } else {
            userInfo.setReadNum(0);
        }

        return R.SUCCESS("获取成功!", userInfo);
    }

    @PostMapping("/count_info")
    public R countInfo(@RequestParam("userId") String userId) {
        List<TravelPO> listTravelAll = commonMapper.listTravelAll(userId);
        List<TravelPO> listCollect = commonMapper.listCollect(userId);

        CountInfoVO countInfoVO = new CountInfoVO();
        if (CollectionUtil.isNotEmpty(listCollect)) {
            countInfoVO.setCollectNum(listCollect.size());
        } else {
            countInfoVO.setCollectNum(0);
        }

        if (CollectionUtil.isNotEmpty(listTravelAll)) {
            countInfoVO.setReadNum(listTravelAll.size());
        } else {
            countInfoVO.setReadNum(0);
        }
        return R.SUCCESS("获取成功!").setData(countInfoVO);
    }


    @PostMapping("/list_advice")
    public R listAdvice() {
        List<AdvicePO> advicePOS = commonMapper.listAdvice();
        AdviceVO adviceVO = new AdviceVO();
        AdvicePO advice1 = advicePOS.get(0);
        if (advice1!=null){
            adviceVO.setTitle1(advice1.getTitle());
            adviceVO.setContent1(advice1.getContent());
        }
        AdvicePO advice2 = advicePOS.get(1);
        if (advice1!=null){
            adviceVO.setTitle2(advice2.getTitle());
            adviceVO.setContent2(advice2.getContent());
        }
        AdvicePO advice3 = advicePOS.get(2);
        if (advice1!=null){
            adviceVO.setTitle3(advice3.getTitle());
            adviceVO.setContent3(advice3.getContent());
        }
        AdvicePO advice4 = advicePOS.get(3);
        if (advice1!=null){
            adviceVO.setTitle4(advice4.getTitle());
            adviceVO.setContent4(advice4.getContent());
        }
        return R.SUCCESS("获取成功!").setData(adviceVO);
    }

}
